package io.wdb.wx.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpClient工具类
 * @author 张俊伟
 *
 */
public class HttpClientUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	private HttpClientUtil(){}
	/**关闭connection
	 * @param response
	 */
	private static void close(HttpResponse response) {
		try {
			if (response == null)
				return;
			if (CloseableHttpResponse.class.isAssignableFrom(response
					.getClass())) {
				((CloseableHttpResponse) response).close();
			}
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
	}
	/**
	 * 获得uri,Get中的参数是使用Map来进行封装的
	 * @param scheme
	 * @param host
	 * @param path
	 * @param uriParams
	 * @return
	 * @throws URISyntaxException
	 */
	public static String getUri(String urlBase,
			Map<String, String> uriParams) throws URISyntaxException {
		StringBuffer str = new StringBuffer();
		if(uriParams != null && !uriParams.isEmpty()){
			for(String key:uriParams.keySet()){
				if(str.length()>0) {
					str.append("&");
				}
				
				try {
					str.append(URLEncoder.encode(key,"UTF-8"));
					str.append("=");
					str.append(URLEncoder.encode(uriParams.get(key),"UTF-8"));
				} catch (UnsupportedEncodingException e) {
				}
			}
		}
		
		if(str.length()<1) {
			return urlBase;
		}
		
		if(urlBase.contains("?")) {
			return urlBase+"&"+str.toString();
		}
		
		return urlBase+"?"+str.toString();
	}
	/**
	 * 将json串中的参数设置到Post体中,传递的参数直接是json串
	 * @param uri
	 * @param jsonPostParams
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void setPostDataJson(HttpPost post,String jsonPostParams) {
		post.setHeader("Content-Type","application/json;charset=utf-8");
		post.setHeader("Accept", "application/json");
		if(jsonPostParams!=null&&!jsonPostParams.trim().equals("")){
			post.setEntity(new StringEntity(jsonPostParams,Charset.forName("UTF-8")));
		}
	}
	/**
	 * 使用xml作为请求数据，返回结果也为xml;
	 * @param uri
	 * @param xmlPostData
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 *//*
	public static String getPostBodyDataXml(String uri,String xmlPostData) {
		HttpPost post = new HttpPost(uri);
		post.setHeader("Content-Type", "text/xml;charset=utf-8");
		if(null!=xmlPostData&&!xmlPostData.trim().equals("")) {
			post.setEntity(new StringEntity(xmlPostData,Charset.forName("UTF-8")));
		}
		return getBody(post);
	}*/
	/**
	 * 
	 * @Method:setPostBodyNameValuePair
	 * @Description:设置post的请求参数
	 * @Time 2017年10月12日 下午3:06:05
	 * @author: Tom
	 */
	public static void setPostBodyNameValuePair(HttpPost post,List<NameValuePair> list) {
		if(list!=null&&list.size()!=0){
			post.setEntity(new UrlEncodedFormEntity(list,Charset.forName("UTF-8")));
		}
	}
	/**
	 * 
	 * @Method:setPostHeardsMaps
	 * @Description:设置请求头
	 * @Time 2017年10月12日 下午3:14:55
	 * @author: Tom
	 * @param post
	 * @param heards
	 */
	public static void setPostHeardsMaps(HttpRequestBase httpRequest,Map<String,String> heards) {
		if(heards!=null&&heards.size()>0) {
			for(String key:heards.keySet()) {
				httpRequest.setHeader(key,heards.get(key));
			}
		}
	}
	/**
	 * 
	 * @Method:getStringBody
	 * @Description:以String方式获取返回的数据
	 * @Time 2017年10月12日 下午3:22:46
	 * @author: Tom
	 * @param request
	 * @return
	 */
	public static String getStringBody(HttpRequestBase request) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse resp;
		try {
			resp = httpClient.execute(request);
			String body = EntityUtils.toString(resp.getEntity(), "UTF-8");
			close(resp);
			return body;
		} catch (IOException e) {
			logger.error("获取Post返回体内容错误：\t"+e.getMessage());
		}
		return null;
	}
}
